//
//  addressMangerVC.m
//  BeautyPicture
//
//  Created by 沈振邦 on 15/8/11.
//  Copyright (c) 2015年 szb. All rights reserved.
//

#import "addressMangerVC.h"
#import "AddressTableViewCell.h"
#import "addAddressVC.h"
#import "BPAddressModel.h"
#import "MBProgressHUD+MJ.h"
#import "AccountTool.h"
#import "BPhttpTool.h"
#import "MJExtension.h"

@interface addressMangerVC ()<AddressTableViewCellDelegate,UITableViewDataSource,UITableViewDelegate,UIAlertViewDelegate>
@property (nonatomic,weak)UILabel *noaddressLabel;

@property (nonatomic,weak)AddressTableViewCell *addCell;

@property (nonatomic,weak)AddressTableViewCell *lastCell;

@property (nonatomic,weak)AddressTableViewCell *currentCell;



/** 存放 所有的 数据 */
@property (nonatomic, strong) NSArray *addressArray;
@end

@implementation addressMangerVC


- (void)viewWillAppear:(BOOL)animated{
    
    self.navigationController.navigationBarHidden = YES;
}

- (void)viewWillDisappear:(BOOL)animated{
    self.navigationController.navigationBarHidden = NO;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.addressArry = [NSMutableArray array];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self downloadData];
    
    [self setUpBaseData];
    
    [self setUpNav];

    [self setUpUIView];
    
    // 创建底部的 "新增地址"
    [self createView];
    
    [self createButton];
    // Do any additional setup after loading the view.
}


// 创建 返回按钮
- (void)createButton{
    
    // 左边按钮
    UIButton *buttonBig = [[UIButton alloc] initWithFrame:CGRectMake(20, 25, 80, 50)];
    buttonBig.backgroundColor = [UIColor clearColor];
    [buttonBig addTarget:self action:@selector(button:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:buttonBig];
    
    UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 23, 23)];
    [button setBackgroundImage:[UIImage imageNamed:@"返回"] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(button:) forControlEvents:UIControlEventTouchUpInside];
    [buttonBig addSubview:button];
    
    
//    UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(20, 25, 23, 23)];
//    [button setBackgroundImage:[UIImage imageNamed:@"返回"] forState:UIControlStateNormal];
//    [button addTarget:self action:@selector(button:) forControlEvents:UIControlEventTouchUpInside];
//    [self.view addSubview:button];
    
    UILabel *name = [[UILabel alloc] initWithFrame:CGRectMake(self.view.frame.size.width / 2 - 30, 20, 100, 30)];
    name.text = @"地址管理";
    name.textColor = BPFenHongColor;
    name.font = [UIFont systemFontOfSize:20];
    [self.view addSubview:name];
    
    // 右边 保存 按钮
    UIButton *buttonSave = [[UIButton alloc] initWithFrame:CGRectMake(self.view.frame.size.width - 50, 20, 60, 50)];
    buttonSave.backgroundColor = [UIColor clearColor];
    [buttonSave addTarget:self action:@selector(buttonRight) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:buttonSave];
    
    UIButton *buttonRight = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 40, 30)];
    [buttonRight setImage:[UIImage imageNamed:@"save"] forState:UIControlStateNormal];
    [buttonRight addTarget:self action:@selector(buttonRight) forControlEvents:UIControlEventTouchUpInside];
    [buttonSave addSubview:buttonRight];
    
    
    UIImageView *im = [[UIImageView alloc] initWithFrame:CGRectMake(0, 60, self.view.frame.size.width, 5)];
    im.image = [UIImage imageNamed:@"波纹线"];
    [self.view addSubview:im];
    
}
// 头部的 两个按钮
- (void)button:(UIButton *)b{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)buttonRight{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)downloadData
{
    [BPhttpTool get:[NSString stringWithFormat:@"%@user/addresslist/uid/%@",BPhttp,[AccountTool account].uid] params:nil success:^(id responseObj) {
        
        self.addressArry = responseObj;
        NSLog(@"总数据 = %@", self.addressArry);
        
        // self.addressArry 里面存储的 是 model
        self.addressArry = [BPAddressModel objectArrayWithKeyValuesArray:responseObj];
        
        [_addressManger deleteAddress:[AccountTool account].uid];
        [_addressManger insertAddress:self.addressArry];
        [self isHaveData];
        [self.addressInfoTableView reloadData];
    } failure:^(NSError *error) {
        
    }];
}

- (void)setUpBaseData
{
    self.addressArry = [NSMutableArray array];
    
    _addressManger = [[CoreDateManager alloc] init];
    self.addressArry = [_addressManger addressAllData:[AccountTool account].uid];
    
    //[self downloadData];
}

- (void)setUpNav
{
    self.title = @"地址管理";
//    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"添加" style:UIBarButtonItemStyleDone target:self action:@selector(addAddress)];
    [self.navigationItem.rightBarButtonItem setImage:[UIImage imageNamed:@"BPdeskViewleftNavImage"]];
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithButtonName:@"返回" tatget:self action:@selector(back)];
}

- (void)back
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)setUpUIView
{
    _addressInfoTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 55, self.view.frame.size.width, self.view.frame.size.height - 60)];
    [self.view addSubview:_addressInfoTableView];
    _addressInfoTableView.backgroundColor = [UIColor whiteColor];
    _addressInfoTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _addressInfoTableView.delegate = self;
    _addressInfoTableView.dataSource = self;
    
    UILabel *noAddressLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, BPScreenNavY, BPScreenW, 30.0f)];
    noAddressLabel.backgroundColor = BPGlobaBGColor;
    noAddressLabel.text = @"没有收货地址，请添加";
    noAddressLabel.textAlignment = NSTextAlignmentCenter;
    noAddressLabel.textColor = [UIColor whiteColor];
    noAddressLabel.font = [UIFont systemFontOfSize:15.0f];
    [self.view addSubview:noAddressLabel];
    self.noaddressLabel = noAddressLabel;
    [self isHaveData];
}

- (void)isHaveData
{
    if (self.addressArry.count == 0) {
        self.noaddressLabel.hidden = NO;
    }else{
        self.noaddressLabel.hidden = YES;
    }
}

- (void)addAddress
{
    addAddressVC *newaddress = [[addAddressVC alloc] init];
    newaddress.block=^(BPAddressModel *model){
        [self.addressArry insertObject:model atIndex:0];
        [_addressInfoTableView insertRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:0 inSection:0]] withRowAnimation:UITableViewRowAnimationFade];
        [self isHaveData];
        [self.addressInfoTableView reloadData];
    };
    
    [self.navigationController pushViewController:newaddress animated:YES];
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.addressArry count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    AddressTableViewCell *cell = [AddressTableViewCell cellWithTableView:tableView];
    cell.delegate = self;
    [cell setUpCellData:_addressArry[indexPath.row]];
    BPAddressModel *model = [[BPAddressModel alloc] init];
    model = _addressArry[indexPath.row];
    if (model.addressid == 0) {
        model.addressid = model.iD;
    }
    
    if (self.Temp - 1 == indexPath.row) {
        cell.yesS.hidden = NO;
    }
    else{
        cell.yesS.hidden = YES;
    }
    
    cell.tag = indexPath.row + 1;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{

    _lastCell.Shi.hidden = YES;
    _currentCell = [tableView cellForRowAtIndexPath:indexPath];
    self.lastCell = [tableView cellForRowAtIndexPath:indexPath];
    _currentCell.Shi.hidden = NO;

    [self.navigationController popViewControllerAnimated:YES];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50;
}

- (void)DeleteCell:(AddressTableViewCell *)addressDeleteCell
{
    _addCell = addressDeleteCell;
    UIAlertView *aletview = [[UIAlertView alloc] initWithTitle:@"提示" message:@"是否删除地址" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"好的", nil];
    [aletview show];
}



- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1) {
        NSIndexPath *indexPath = [_addressInfoTableView indexPathForCell:_addCell];
        
        BPAddressModel *model = self.addressArry[indexPath.row];
        model.status = 0;
        if (model.addressid == 0) {
            model.addressid = model.iD;
        }
        [AccountTool addOrChangeOrdeleteAddress:model success:^(paramAddress *result) {
            
        } failure:^(NSError *error) {
            BPLog(@"地址删除错误");
        }];
        [_addressManger deleteOneAddress:model];
        [_addressArry removeObjectAtIndex:indexPath.row];
        [_addressInfoTableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
        [self isHaveData];
    }
    
}


- (void)editAddress:(AddressTableViewCell *)editCell
{
    NSIndexPath *indexPath = [_addressInfoTableView indexPathForCell:editCell];
    addAddressVC *change = [[addAddressVC alloc] init];
    BPAddressModel *model = _addressArry[indexPath.row];
    if (model.addressid == 0) {
         model.addressid = model.iD;
    }
    change.addressModel = model;
    change.block=^(BPAddressModel *model){
        [_addressArry replaceObjectAtIndex:indexPath.row withObject:model];
        [_addressInfoTableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    };
    [self.navigationController pushViewController:change animated:YES];
}




- (void)createView{
    UIButton *buttons = [[UIButton alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height - 40, self.view.frame.size.width, 40)];
    buttons.backgroundColor = BPGlobaThemeColor;
    [buttons setTitle:@"新增地址" forState:UIControlStateNormal];
    [buttons setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [buttons addTarget:self action:@selector(addAddress) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:buttons];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
